package plotter

import (
	"code.google.com/p/plotinum/plot"
	"code.google.com/p/plotinum/vg"
	"image/color"
	"math"
)

// PieChartSlice implements the Plotter interface, drawing
// a single pie chart slice with value between 0 and 1.
type PieChartSlice struct {
	Value float64

	// Color is the color of the slice.
	Color color.Color

	// Start is the starting point of the slice (antclockwise from the right, 0-1)
	Start float64

	// Radius is the radius of the slice , from 0 to 0.5 
	Radius float64
}

// NewPieChartSlice creates as new piechart plotter for
// the given start, value and radius
func NewPieChartSlice(start float64, value float64, radius float64) *PieChartSlice {
	return &PieChartSlice{
		Value:  value,
		Start:  start,
		Color:  color.Black,
		Radius: radius,
	}
}

// Plot implements the Plot method of the plot.Plotter interface.
func (pcs *PieChartSlice) Plot(da plot.DrawArea, plt *plot.Plot) {
	trX, trY := plt.Transforms(&da)

	da.SetColor(pcs.Color)
	cx := trX(0.5)
	cy := trY(0.5)

	rad := trY(pcs.Radius)
	var p vg.Path
	p.Move(cx, cy)
	start := 2 * math.Pi * pcs.Start
	end := 2 * math.Pi * pcs.Value
	p.Arc(cx, cy, rad, start, end)
	p.Close()
	da.Fill(p)
}

func (pcs *PieChartSlice) Thumbnail(da *plot.DrawArea) {
	pts := []plot.Point{
		{da.Min.X, da.Min.Y},
		{da.Min.X, da.Max().Y},
		{da.Max().X, da.Max().Y},
		{da.Max().X, da.Min.Y},
	}
	poly := da.ClipPolygonY(pts)
	da.FillPolygon(pcs.Color, poly)

	pts = append(pts, plot.Point{da.Min.X, da.Min.Y})
	outline := da.ClipLinesY(pts)
	da.StrokeLines(DefaultLineStyle, outline...)
}

func (p *PieChartSlice) DataRange() (xmin, xmax, ymin, ymax float64) {
	return 0.0, 1.0, 0.0, 1.0
}
